const mongoose = require('mongoose');

const orderSchema = new mongoose.Schema({
  // 订单基本信息
  orderNumber: {
    type: String,
    required: true,
    unique: true
  },
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  
  // 商品信息
  productType: {
    type: String,
    enum: ['tour', 'hotel'],
    required: true
  },
  productId: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    refPath: 'productType'
  },
  productSnapshot: {
    // 保存下单时的商品快照，避免商品信息变更影响订单
    type: mongoose.Schema.Types.Mixed,
    required: true
  },
  
  // 订单详情
  quantity: {
    type: Number,
    default: 1,
    min: 1
  },
  unitPrice: {
    type: Number,
    required: true
  },
  totalPrice: {
    type: Number,
    required: true
  },
  currency: {
    type: String,
    default: '¥'
  },
  
  // 旅行/住宿日期信息
  startDate: {
    type: Date,
    required: true
  },
  endDate: {
    type: Date,
    required: true
  },
  
  // 客户信息
  customerInfo: {
    name: {
      type: String,
      required: true
    },
    phone: {
      type: String,
      required: true
    },
    email: {
      type: String,
      required: true
    },
    remarks: String
  },
  
  // 订单状态
  status: {
    type: String,
    enum: ['pending', 'confirmed', 'cancelled', 'completed', 'refunded'],
    default: 'pending'
  },
  
  // 支付信息
  paymentStatus: {
    type: String,
    enum: ['unpaid', 'paid', 'refunded'],
    default: 'unpaid'
  },
  paymentMethod: {
    type: String,
    enum: ['alipay', 'wechat', 'bank_card', 'cash'],
    default: 'alipay'
  },
  
  // 时间戳
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  },
  
  // 特殊需求和备注
  specialRequests: [{
    type: String
  }],
  
  // 取消原因（如果已取消）
  cancellationReason: String,
  
  // 评价信息
  review: {
    rating: {
      type: Number,
      min: 1,
      max: 5
    },
    comment: String,
    reviewDate: Date
  }
}, {
  timestamps: true,
  collection: 'orders'
});

// 虚拟字段 - 计算订单天数
orderSchema.virtual('duration').get(function() {
  if (this.startDate && this.endDate) {
    const diffTime = this.endDate - this.startDate;
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  }
  return 0;
});

// 索引优化
orderSchema.index({ userId: 1, createdAt: -1 });
orderSchema.index({ orderNumber: 1 });
orderSchema.index({ status: 1 });
orderSchema.index({ productType: 1, productId: 1 });

// 中间件 - 保存前更新 updatedAt
orderSchema.pre('save', function(next) {
  this.updatedAt = new Date();
  next();
});

// 静态方法 - 生成订单号
orderSchema.statics.generateOrderNumber = function() {
  const timestamp = Date.now().toString();
  const random = Math.random().toString(36).substr(2, 6).toUpperCase();
  return `ORD${timestamp}${random}`;
};

// 实例方法 - 格式化订单信息
orderSchema.methods.getFormattedInfo = function() {
  return {
    orderNumber: this.orderNumber,
    productType: this.productType === 'tour' ? '旅游攻略' : '酒店预订',
    productName: this.productSnapshot.name || this.productSnapshot.title,
    totalPrice: `${this.currency}${this.totalPrice}`,
    status: this.getStatusText(),
    duration: this.duration,
    createdAt: this.createdAt.toLocaleString('zh-CN')
  };
};

// 实例方法 - 获取状态文本
orderSchema.methods.getStatusText = function() {
  const statusMap = {
    'pending': '待确认',
    'confirmed': '已确认',
    'cancelled': '已取消',
    'completed': '已完成',
    'refunded': '已退款'
  };
  return statusMap[this.status] || '未知状态';
};

module.exports = mongoose.model('Order', orderSchema); 